from django.shortcuts import render
from django.http import HttpResponse,Http404,JsonResponse
from . models import Users,Citys
from django.core.urlresolvers import reverse
# Create your views here.
def index(request):
    return render(request,'index.html')
# 用户添加信息
def user_add(request):
    return render(request,'user/add.html')
#用户信息添加的执行
def user_insert(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    Users.objects.create(**data)
    res = "<script>alert('添加数据成功');location.href='{}'</script>".format(reverse('user_list'))
    return HttpResponse(res)
#用户信息的显示列表界面
def user_list(request):
    data = Users.objects.all()
    content = {'users':data}
    return render(request,'user/list.html',content)
#用户信息的删除
def user_del(request,uid):
    ob = Users.objects.get(id = uid)
    ob.delete()
    res = "<script>alert('删除数据成功');location.href='{}'</script>".format(reverse('user_list'))
    return HttpResponse(res)
#用户信息的编辑页面
def user_edit(request,uid):
    ob = Users.objects.get(id = uid)
    content = {'uinfo':ob}
    return render(request,'user/edit.html',content)
#用户信息的更新执行
def user_update(request):
    uid = request.POST['uid']
    ob = Users.objects.get(id = uid)
    ob.username = request.POST['username']
    ob.weight = request.POST['weight']
    ob.height = request.POST['height']
    ob.age = request.POST['age']
    ob.sex = request.POST['sex']
    ob.save()
    res = "<script>alert('更新数据成功');location.href='{}'</script>".format(reverse('user_list'))
    return HttpResponse(res)
#城市的三级联动
def citys(request):
    data = Citys.objects.filter(upid = 0)
    return render(request,'citys.html',{'data':data})
#城市三级联动获取县市级的数据
def getcitys(request):
    upid = request.GET.get('id')
    data = Citys.objects.filter(upid=upid).values()
    return JsonResponse(list(data),safe=False)
